package com.inspector.app.ui.flight.mapsearch.poi

import android.content.Context
import com.amap.api.location.AMapLocationClient
import com.amap.api.maps.MapsInitializer
import com.amap.api.services.core.PoiItem
import com.amap.api.services.core.ServiceSettings
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import com.blankj.utilcode.util.NetworkUtils
import com.huawei.location.lite.common.util.NetworkUtil
import com.inspector.app.di.location.CustomCoordinateType
import com.inspector.app.ui.flight.mapsearch.MapSearchInstance
import com.inspector.app.util.LogUtil
import com.inspector.app.util.ToastUtil
import com.inspector.app.util.UUIDGenerator


/**
 * 高德地图集成相关
 * @author pank 2023/4/4
 */
class GDSearchInstance {

    //[高德地图SDK初始化]
    private val TAG = "GDMapInstance"
    fun setApiKey(apiKey: String) {
        //[高德地图SDK初始化]
        MapsInitializer.setApiKey(apiKey)
        //[高德搜索SDK初始化]
        ServiceSettings.getInstance().setApiKey(apiKey)
        //[高德定位SDK初始化]
        AMapLocationClient.setApiKey(apiKey)

        // [需要调用隐私协议接口,否则可能会崩溃,使用需要捕获异常]
        //[高德-隐私政策合规]
        //ServiceSettings.updatePrivacyShow(context, true, true)
        //ServiceSettings.updatePrivacyAgree(context, true)
    }

    //[高德-隐私政策合规]
    fun updatePrivacy(context: Context) {
        ServiceSettings.updatePrivacyShow(context, true, true)
        ServiceSettings.updatePrivacyAgree(context, true)
    }

    //[高德关键字搜索-https://lbs.amap.com/api/android-sdk/guide/map-data/poi 文档]
    fun getPoiSearch(
        context: Context,
        keyWord: String,
        listener: (MutableList<MapSearchPoi>?) -> Unit
    ) {
        try {
            if (!NetworkUtil.isNetworkAvailable(context)) {
                ToastUtil.getInstance().showToast("当前搜索类型不支持离线使用")
                listener(null)
                return
            }
            //[第二个参数为搜索类型]
            val query = PoiSearch.Query(keyWord, "")
            query.pageSize = 50
            query.pageNum = 0
            //[避免省市县无法搜索]
            query.extensions = PoiSearch.EXTENSIONS_ALL
            val poiSearch = PoiSearch(context, query)
            poiSearch.setOnPoiSearchListener(object : PoiSearch.OnPoiSearchListener {
                override fun onPoiSearched(poiResult: PoiResult?, code: Int) {
                    LogUtil.e(TAG, "onPoiSearched code:$code poiResult:$poiResult")
                    if (code != 1000) {
                        ToastUtil.getInstance().showToast("错误码:$code,请您联系我们")
                        listener(null)
                        return
                    }
                    listener(swapPoiItems(poiResult?.pois, keyWord))
                }

                override fun onPoiItemSearched(poiItem: PoiItem, code: Int) {
                    LogUtil.e(TAG, "onPoiItemSearched code:$code poiItem:$poiItem")
                }
            })
            poiSearch.searchPOIAsyn()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //[处理高德地图POI搜索返回结果——需将高德地图经纬度转成84经纬度]
    private fun swapPoiItems(
        poiItems: MutableList<PoiItem>?,
        searchTxt: String
    ): MutableList<MapSearchPoi> {
        if (poiItems.isNullOrEmpty()) {
            ToastUtil.getInstance().showToast("暂无搜索数据,请您换个关键字试试")
            return mutableListOf()
        }
        val searchItems = poiItems
            .mapNotNull { poiItem ->
//            LogUtil.e(TAG,"poiId:${poiItem.poiId} title:${poiItem.title} adName:${poiItem.adName} cityName:${poiItem.cityName} provinceName:${poiItem.provinceName}")
                var mapSearchPoi: MapSearchPoi? = null
                try {
                    mapSearchPoi = MapSearchPoi()
                    mapSearchPoi.id =
                        if (poiItem.poiId.isNullOrEmpty()) UUIDGenerator.generate() else poiItem.poiId
                    mapSearchPoi.name = poiItem.title
                    mapSearchPoi.colorSpan =
                        MapSearchInstance.getColorSpan(poiItem.title, searchTxt)
                    mapSearchPoi.searchNameWeight =
                        MapSearchInstance.containsSearchWeight(poiItem.title, searchTxt)
                    mapSearchPoi.coordType = CustomCoordinateType.GAODE
                    mapSearchPoi.lat = poiItem.latLonPoint.latitude
                    mapSearchPoi.lng = poiItem.latLonPoint.longitude
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                mapSearchPoi
            }.toMutableList()
        return searchItems
    }

    companion object {
        @JvmStatic
        val instance by lazy { GDSearchInstance() }
    }
}